package cracker.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 网络服务器
 * @author ljh_2018
 *
 */
public class NetRobotServer {

	private static BufferedReader br=null;
	private static PrintWriter pw=null;
	private final static int PORT = 10880;
	private static ServerSocket server = null;
	private final static NetRobotServer net = new NetRobotServer();
	private static Map<String,String> brainStorage = new HashMap<>();
	private static Map<String,Socket> socketTable = new HashMap<>();

	static {
		//大脑初始库
		brainStorage.put("对不起，我还听不懂您的意思","是吗？");
		brainStorage.put("Hello", "hello 你好！");
		brainStorage.put("你好啊","谢谢，我很好");
		try {
			server = new ServerSocket(PORT);
			System.out.println("服务器启动成功");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class ServerThread extends Thread {
		Socket socket = null;

		public ServerThread(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			try {
				br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
				pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
				String lastKey = "对不起，我还听不懂您的意思";
				while(true){
					String string=br.readLine();   
					if(string==null || string.equals("exit")){
						pw.append("服务端: 哎呀，你要走啦！再见咯！\n");
						pw.flush();
						break;
					} else {
						if(string.startsWith("address:")) {
							string = string.substring(8);
							socketTable.putIfAbsent(string, socket);
						}
						System.out.println("Server读到："+string);
					}
					brainStorage.put(lastKey, string);
					lastKey = brainStorage.getOrDefault(string, "对不起，我还听不懂您的意思");
					pw.append("服务端："+brainStorage.getOrDefault(string, "对不起，我还听不懂您的意思")+"\n");
					pw.flush();
				}
			} catch (IOException e) {
				System.out.println("服务器连接异常");
			} finally {
				try {
					br.close();
					pw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}

	}

	public static NetRobotServer getInstance() {
		return net;
	}

	private void start() {
		while(true) {
			try {
				//接收socket
				Socket s = server.accept();
				System.out.println("接收到第"+socketTable.size()+"个连接");
				ServerThread thread = new ServerThread(s);
				thread.start();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		NetRobotServer.getInstance().start();
	}

}
